package otw.dao.ibatis.typehandler;

import com.ibatis.sqlmap.client.extensions.ParameterSetter;
import com.ibatis.sqlmap.client.extensions.ResultGetter;
import com.ibatis.sqlmap.client.extensions.TypeHandlerCallback;
import java.sql.SQLException;

public class YesNoTypeHandlerCallback implements TypeHandlerCallback {

	public static final String YES = "Y";

	public static final String NO = "N";

	public void setParameter(ParameterSetter setter, Object parameter) throws SQLException {
		setter.setString(booleanToYesNo((Boolean) parameter));
	}

	public Object getResult(ResultGetter getter) throws SQLException {
		return yesNoToBoolean(getter.getString());
	}

	public Object valueOf(String s) {
		return yesNoToBoolean(s);
	}

	private Boolean yesNoToBoolean(String s) {
		if (null == s) {
			return Boolean.FALSE;
		}
		if (YES.equalsIgnoreCase(s)) {
			return Boolean.TRUE;
		} else if (NO.equalsIgnoreCase(s)) {
			return Boolean.FALSE;
		} else {
			throw new IllegalArgumentException("Could not convert " + s + " to a boolean value. " + "Valid arguments are 'Y' and 'N'.");
		}
	}

	private String booleanToYesNo(Boolean b) {
		if (b == null) {
			return NO;
		} else if (b) {
			return YES;
		} else {
			return NO;
		}
	}
}